package com.google.gwt.livinglife.client;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ErrorEvent;
import com.google.gwt.event.dom.client.ErrorHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.livinglife.client.data.GroupIdData;
import com.google.gwt.livinglife.client.data.LivingLifeUserData;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
 * This class is the UI element for giving a user the ability to change their account settings.
 * 
 * @author amitprakash
 *
 */
public class UserSettings {
	HorizontalPanel main_panel = new HorizontalPanel();
	VerticalPanel display_panel = new VerticalPanel();
	Image picture = new Image();
	Label caption = new Label("no picture");
	VerticalPanel form_panel = new VerticalPanel();
  Label nickname_box_label = new Label("How should we address you here");
  TextBox nickname_box = new TextBox();
  Label picture_label = new Label("Picture url to put a face to your name");
  TextBox picture_url_box = new TextBox();
  Label communication_email_label = new Label("Communication email");
  TextBox communication_box = new TextBox();
	Button submit_button = new Button("Submit", new ClickHandler() {
		public void onClick(ClickEvent event) {
			handleSubmit();
		}
	});
	LivingLifeUserData  user_data;
	class GroupRow extends HorizontalPanel {
		Label group_name_label = new Label();
		ToggleButton remove_button = new ToggleButton("Remove", "Undo remove");
		GroupIdData group_id_data;
		
		public GroupRow(GroupIdData gid) {
			group_id_data = gid;
			group_name_label.setText(gid.getGroup_name());
			this.add(remove_button);
			this.add(group_name_label);
		}
		Boolean shouldRemove() {
			return remove_button.isDown();
		}
		GroupIdData getGroupIdData() {
			return group_id_data;
		}
	}

	ArrayList<GroupRow> groups = new ArrayList<GroupRow>();
	
	public UserSettings() {
		// Hook up an error handler, so that we can be informed if the image fails
		// to load.
		assemble();
		main_panel.setVisible(false);
		picture.addErrorHandler(new ErrorHandler() {
			@Override
			public void onError(ErrorEvent event) {
				Window.alert("Error in loading the image" + event.toDebugString());
				picture.setUrl("images/face.png");
			}
		});
	}
	private void assemble() {
		main_panel.add(form_panel);
		main_panel.add(display_panel);
		display_panel.add(picture);
		display_panel.add(caption);
		form_panel.add(nickname_box_label);
		form_panel.add(nickname_box);
		form_panel.add(picture_label);
		form_panel.add(picture_url_box);
		form_panel.add(communication_email_label);
		form_panel.add(communication_box);
		form_panel.add(submit_button);
		picture.setHeight("4in");
		nickname_box.setVisibleLength(50);
		picture_url_box.setVisibleLength(50);
		communication_box.setVisibleLength(50);
	}
	
	public void set_user_data(LivingLifeUserData data) {
		user_data = data;
		if (data == null) {
			main_panel.setVisible(false);
			return;
		}
		if (data.getPicture_url() == null || data.getPicture_url().length() == 0) {
			picture.setUrl("images/face.png");
			picture.setPixelSize(30, 30);
		} else {
			picture.setUrl(data.getPicture_url());
		}
		nickname_box.setText(data.getNickname());		
		picture_url_box.setText(data.getPicture_url());		
		communication_box.setText(data.getCommunication_email());
		//delete old group buttons
		Iterator<GroupRow> group_row_iter = groups.iterator();
		while(group_row_iter.hasNext()) {
			form_panel.remove(group_row_iter.next());
		}
		groups.clear();
		Iterator<GroupIdData> iter = data.getGroups().iterator();
		while(iter.hasNext()) {
			GroupRow gr = new GroupRow(iter.next());
			groups.add(gr);
			form_panel.add(gr);
		}
		caption.setText(data.getNickname() + " (" + data.getCommunication_email() + ")");
		main_panel.setVisible(true);
	}
	
	private void handleSubmit() {
		user_data.setCommunication_email(communication_box.getText());
		user_data.setNickname(nickname_box.getText());
		user_data.setPicture_url(picture_url_box.getText());
		Iterator<GroupRow> iter = groups.iterator();
		while(iter.hasNext()) {
			GroupRow gr = iter.next();
			if (gr.shouldRemove()) {
				user_data.getGroups().remove(gr.group_id_data);
			}
		}
		LivingLifeServiceAsync living_life_service = GWT.create(LivingLifeService.class);
		try {
			living_life_service.updateUserData(user_data,
					new AsyncCallback<Void>() {
				public void onFailure(Throwable error) {
					handleError(error);
				}
				public void onSuccess(Void result) {				
				}
			});
		} catch (NotLoggedInException e) {
			
			handleError(e);
		}
		set_user_data(user_data);
	}
	private void handleError(Throwable error) {
		Window.alert(error.getMessage());
		if (error instanceof NotLoggedInException) {
			// TODO(amit) make the url the login url
			Window.Location.replace("http://living-life.appspot.com");
		}
	}

	public Widget getMainPanel() {
		return main_panel;
	}
}
